<?php
/**
 * Zend Framework (http://framework.zend.com/)
 *
 * @link      http://github.com/zendframework/ZendSkeletonApplication for the canonical source repository
 * @copyright Copyright (c) 2005-2013 Zend Technologies USA Inc. (http://www.zend.com)
 * @license   http://framework.zend.com/license/new-bsd New BSD License
 */

namespace Application\Controller;

use Zend\Form\Form;
use Predis\Client;
use Zend\Mvc\Controller\AbstractActionController;
use Zend\Stdlib\ResponseInterface as Response;
use Zend\Stdlib\Parameters;
use Zend\View\Model\ViewModel;
use Zend\Authentication\AuthenticationService;
use SanAuthWithDbSaveHandler\Storage\IdentityManagerInterface;
use Zend\View\Model\JsonModel;
use ZfcUser\Model\TuserTable;
use ZfcUser\Model\Tuser;
use ZfcUser\Model\Torders;
use ZfcUser\Model\TordersTable;
use Zend\Cache\StorageFactory;
use Zend\Session\Container;


class IndexController extends AbstractActionController
{
	
	public function headerAction($params)
    {
		$baseUrls = $this->getServiceLocator()->get('config');
		$baseUrlArr = $baseUrls['urls'];
		$baseUrl = $baseUrlArr['baseUrl'];
		$basePath = $baseUrlArr['basePath'];
		$uploadPath = $baseUrlArr['uploadPath'];
		$paypalUrl = $baseUrlArr['paypalUrl'];
		$paypalid = $baseUrlArr['paypalid'];
		return $this->layout()->setVariable(
			"headerarray",array(
				'baseUrl' 		=> 	$baseUrl,
				'basePath'		=>	$basePath,
				'uploadPath'	=>	$uploadPath,
				'paypalUrl'		=>	$paypalUrl,
				'paypalid'		=>	$paypalid,
			)
		);
	}
	public function indexAction()
    {  
		$baseUrls = $this->getServiceLocator()->get('config');
		$baseUrlArr = $baseUrls['urls'];
		$paypalUrl = $baseUrlArr['paypalUrl'];
		$paypalid = $baseUrlArr['paypalid'];
		$baseUrl = $baseUrlArr['baseUrl'];
		$result = new ViewModel(array(					
			'paypalid' 	=> $paypalid,
			'paypalUrl' => $paypalUrl,
			'baseUrl'	 => $baseUrl,
			
		));
		return $result;
	}
	public function logoutAction()
    {  
		$SESSION = new Container('user');	
		$SESSION['loginNum2']='';
		$SESSION['uname']='';
		return $this->redirect()->toUrl('index');	
    }
	public function countriesAction()
    {  
			
    } 
	
	public function footerAction(){
		
	}
	public function learnAction()
    {
        return new ViewModel();
    }
	public function buyAction()
    {
        return new ViewModel();
    }
	public function confirmAction()
    {
		return new ViewModel();
    }
	public function payAction()
    {
        return new ViewModel();
    }
	
	public function orderAction()
    {
		// Get User Id
		$uesrId='';
		if(isset($_SESSION['user'])){
			$uesrId=$_SESSION['user']['userId'];
		}else{
			$token = $this->getUniqueCode('10');
			$table = $this->getServiceLocator()->get('ZfcUser\Model\TuserTable');
			$user = $table->addUser($_POST,$token);
			$uesrId=$user->user_id;
		}
		//End
		
		// Insert Order
		//$table = $this->getServiceLocator()->get('ZfcUser\Model\TordersTable');
		//$order = $table->addOrder($_POST,$uesrId);
		//$orderId=$order->order_id; 
		// End
		
		$data=array();
		if(isset($_POST['name'])){
			$data['user_name']=$_POST['name'];
			$data['user_address']=$_POST['address'];
			$data['user_zipcode']="522235";
			$data['user_city']=$_POST['city'];
			$data['user_state']=$_POST['state'];
			$data['user_country']="Ind";
			$data['user_phone']=$_POST['mobileNo'];
			$data['user_email']=$_POST['emailId'];
			$data['user_id']='"'.$uesrId.'"';
			$data['modelno']="M1";
			$data['key']="ebskey";
			$data['account_id']="5880";
			$data['finalamount']=$_POST['total'];
			$data['order_no']="123456";
			$data['return_url']="http://extramarks.local/response?DR={DR}";
			$data['mode']="TEST";
			$data['hash'] = $data['key']."|".$data['account_id']."|".$data['finalamount']."|".$data['order_no']."|".$data['return_url']."|".$data['mode'];
			$data['secure_hash'] = md5($data['hash']);
		}
        $_SESSION['data']=$data;
		$result = new JsonModel(array(					
			'output' => 'success',
		));
		return $result;
    }
	public function paymentAction()
    {
		$uesrId='';
		$table = $this->getServiceLocator()->get('ZfcUser\Model\TuserTable');
		if(isset($_SESSION['user'])){
			$user = $table->addUser($_POST);
			$uesrId=$_SESSION['user']['userId'];
		}else{
			$token = $this->getUniqueCode('10');
			$user = $table->addUser($_POST,$token);
			$uesrId=$user->user_id;
		}
		$statestable = $this->getServiceLocator()->get('ZfcUser\Model\TstateTable');
		$statedetails=$statestable->getStateName($_POST['state']);
		$statename=$statedetails->state_name;
		$countrytable=$this->getServiceLocator()->get('ZfcUser\Model\TcountryTable');
		$countrydetails=$countrytable->getCountryName($_POST['country']);
		$countryname=$countrydetails->country_name;
		$transactiontable=$this->getServiceLocator()->get('Package\Model\TusertransactionTable');
		$paymenttype="CCAVENUE";
		$status='0';
		$transaction_id=$transactiontable->addTransaction($paymenttype,$status);
		//echo $transactiondetails;exit;
		$data=array();
				$data['Merchant_Id'] = "M_extramar_6654";
				$data['Redirect_Url'] = "http://".$_SERVER['HTTP_HOST']."/response";
				$data['WorkingKey'] = "22vjweje2fpjq8sw5s9z76zwlz5mbtgw";
				$data['Amount']=$_POST['total'];
				$data['Order_Id'] = $this->getUniqueCode(6)."-".$transaction_id;
				$data['Checksum'] = $this->getCheckSum($data['Merchant_Id'],$data['Amount'],$data['Order_Id'] ,$data['Redirect_Url'],$data['WorkingKey']);
				$data['billing_cust_name']=$_POST['name'];
				$data['billing_cust_address']=$_POST['address'];
				$data['billing_cust_state']=$statename;
				$data['billing_cust_city']="";
				$data['billing_cust_country']=$countryname;
				$data['billing_cust_tel']=$_POST['phone'];
				$data['billing_cust_email']=$_POST['emailId'];
				$data['delivery_cust_name']=$_POST['name'] ;
				$data['delivery_cust_address']=$_POST['address'];
				$data['delivery_cust_state'] = $statename;
				$data['delivery_cust_country'] = $countryname;
				$data['delivery_cust_tel']=$_POST['phone'];
				$data['delivery_cust_notes']="Testing";
				$data['Merchant_Param']="Test";
				$data['billing_city'] = "";
				$data['billing_zip'] = "";
				$data['delivery_city'] = "";
				$data['delivery_zip'] = "";
		$result = new ViewModel(array(					
			'data' => $data,
		));
		return $result;
    }
	function getchecksum($MerchantId,$Amount,$OrderId ,$URL,$WorkingKey)
	{
		$str ="$MerchantId|$OrderId|$Amount|$URL|$WorkingKey";
		$adler = 1;
		$adler = $this->adler32($adler,$str);
		return $adler;
	}

	function verifychecksum($MerchantId,$OrderId,$Amount,$AuthDesc,$CheckSum,$WorkingKey)
	{
		$str = "$MerchantId|$OrderId|$Amount|$AuthDesc|$WorkingKey";
		$adler = 1;
		$adler = $this->adler32($adler,$str);
		
		if($adler == $CheckSum)
			return "true" ;
		else
			return "false" ;
	}

	function adler32($adler , $str)
	{
		$BASE =  65521 ;

		$s1 = $adler & 0xffff ;
		$s2 = ($adler >> 16) & 0xffff;
		for($i = 0 ; $i < strlen($str) ; $i++)
		{
			$s1 = ($s1 + Ord($str[$i])) % $BASE ;
			$s2 = ($s2 + $s1) % $BASE ;
				//echo "s1 : $s1 <BR> s2 : $s2 <BR>";

		}
		return $this->leftshift($s2 , 16) + $s1;
	}

	function leftshift($str , $num)
	{
		$str = DecBin($str);

		for( $i = 0 ; $i < (64 - strlen($str)) ; $i++)
			$str = "0".$str ;

		for($i = 0 ; $i < $num ; $i++) 
		{
			$str = $str."0";
			$str = substr($str , 1 ) ;
			//echo "str : $str <BR>";
		}
		return $this->cdec($str) ;
	}

	function cdec($num)
	{

		for ($n = 0 ; $n < strlen($num) ; $n++)
		{
		   $temp = $num[$n] ;
		   $dec =  @$dec + $temp*pow(2 , strlen($num) - $n - 1);
		}

		return @$dec;
	}
	public function responseAction()
    {
		//echo "<pre>";print_r($_SESSION['package']);exit;
		$packagetable=$this->getServiceLocator()->get('Package\Model\TuserpackageTable');
		$paymenttype="CCAVENUE";
		$status='1';
		$transactiontable=$this->getServiceLocator()->get('Package\Model\TusertransactionTable');
		$paymenttype="CCAVENUE";
		$status='1';
		$transactiondetails=$transactiontable->updateTransaction($paymenttype,$status,$_REQUEST);
		$transactiondetails=$transactiontable->updateTransaction($paymenttype,$status,$_REQUEST);
		$orderdetails=explode("-",$_REQUEST['Order_Id']);
		$transaction_id=$orderdetails[1];
		$user_package=array();
		if($_REQUEST['AuthDesc']=="Y" || $_REQUEST['AuthDesc']=="B")
		{
			foreach($_SESSION['package'] as $key=>$packagedetails)
			{
				$user_package[$packagedetails['package_name']]=$packagetable->adduserpackages($_SESSION['user']['userId'],$transaction_id,$key,$packagedetails);
			}
			unset($_SESSION['package']);
		}
        return new ViewModel(
			array(
				'response'=>$_REQUEST,
				'user_package'=>$user_package,
			)
		);
    }
	
	public function getUniqueCode($length = "")
	{
		$code = md5(uniqid(rand(), true));
		if ($length != "")
		return substr($code, 0, $length);
		else
		return $code;
	}
	public function changeCountryNameAction(){	
		$countryname=$_POST['country_name'];			
		if(isset($_SESSION['ip_countryname'])){
			unset($_SESSION['ip_countryname']);
			$_SESSION['ip_countryname']=$countryname;	
		}			
		$result = new JsonModel(array(					
			'country_name' => $countryname,
			'success'=>'success',
		));			
		return $result;
	}
	
}
